package com.yy.bootdemo.admin.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yy.bootdemo.admin.dao.RoleUserDao;
import com.yy.bootdemo.admin.dao.UserDao;
import com.yy.bootdemo.admin.dao.UserJobDao;
import com.yy.bootdemo.admin.dto.MenuIndexDto;
import com.yy.bootdemo.admin.entity.MyRoleUser;
import com.yy.bootdemo.admin.entity.MyUser;
import com.yy.bootdemo.admin.entity.MyUserJob;
import com.yy.bootdemo.admin.service.UserService;
import com.yy.bootdemo.common.exceptionhandler.MyException;
import com.yy.bootdemo.common.utils.Result;
import com.yy.bootdemo.common.utils.ResultCode;
import com.yy.bootdemo.common.utils.UserConstants;
import com.yy.bootdemo.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yy
 * @createTime 2022/8/1
 */
@Service
public class UserServiceImpl  extends ServiceImpl<UserDao, MyUser> implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleUserDao roleUserDao;

    @Autowired
    private UserJobDao userJobDao;



    @Override
    public MyUser getUserById(Integer userId) {
        return userDao.getUserById(userId);
    }

    @Override
    public void checkUserAllowed(MyUser user) {
        //&& user.isAdmin()
        if (!StringUtils.isEmpty(user.getUserId()) )
        {
            throw new MyException(ResultCode.ERROR,"不允许操作超级管理员用户");
        }
    }

    @Override
    public String checkPhoneUnique(MyUser myUser) {
        Integer userId = ObjectUtil.isEmpty(myUser.getUserId()) ? -1: myUser.getUserId();
        LambdaQueryWrapper<MyUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MyUser::getPhone,myUser.getPhone());
        MyUser info = userDao.selectOne(lambdaQueryWrapper);
       // MyUser info = userDao.checkPhoneUnique(myUser.getPhone());
        if (ObjectUtil.isNotEmpty(info) && !info.getUserId().equals(userId))
        {
            return UserConstants.USER_PHONE_NOT_UNIQUE;
        }
        return UserConstants.USER_PHONE_UNIQUE;
    }

    @Override
    public String checkUserNameUnique(MyUser myUser) {
        Integer userId = ObjectUtil.isEmpty(myUser.getUserId()) ? -1: myUser.getUserId();
        LambdaQueryWrapper<MyUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MyUser::getUserId,myUser.getUserId());
        MyUser info = userDao.selectOne(lambdaQueryWrapper);
       // MyUser info = userDao.checkUsernameUnique(myUser.getUserName());
        if (ObjectUtil.isNotEmpty(info) && !info.getUserId().equals(userId))
        {
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }


    @Override
    public R save(MyUser myUser, Integer roleId) {
        if(roleId!= null){
            userDao.save(myUser);
            MyRoleUser myRoleUser = new MyRoleUser();
            myRoleUser.setRoleId(roleId);
            myRoleUser.setUserId(myUser.getUserId().intValue());
            roleUserDao.save(myRoleUser);
            insertUserPost(myUser);
            return R.ok("添加成功，初始密码123456");
        }

        return R.error("添加失败");
    }



    @Override
    public MyUser getUserByName(String userName) {
        return userDao.getUser(userName);
    }

    @Override
    public List<MenuIndexDto> getUserlist() {
        return userDao.getUserlist();
    }

    @Override
    public void updateUser(MyUser myUser) {
        MyRoleUser myRoleUser=new MyRoleUser();
        myRoleUser.setUserId(myUser.getUserId());
        myRoleUser.setRoleId(myUser.getRoleId());
        this.roleUserDao.updateById(myRoleUser);
        this.userDao.updateById(myUser);
    }



    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(MyUser user)
    {
        Integer[] jobs = user.getJobIds();

        if (ArrayUtil.isNotEmpty(jobs))
        {
            // 新增用户与岗位管理
            List<MyUserJob> list = new ArrayList<MyUserJob>();
            for (Integer jobId : jobs)
            {
                MyUserJob up = new MyUserJob();
                up.setUserId(user.getUserId());
                up.setJobId(jobId);
                list.add(up);
            }
            if (list.size() > 0)
            {
                userJobDao.batchUserJob(list);
            }
        }
        return;
    }

    @Override
    public void saveUser(MyUser myUser) {
        if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(this.checkPhoneUnique(myUser))){
            throw new MyException("手机号已存在");
        }
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(this.checkUserNameUnique(myUser))){
            throw new MyException("用户名已存在");
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        myUser.setPassword(bCryptPasswordEncoder.encode("123456"));
        this.userDao.insert(myUser);
        MyRoleUser myRoleUser=new MyRoleUser();
        myRoleUser.setUserId(myUser.getUserId());
        myRoleUser.setRoleId(myUser.getRoleId());
        this.roleUserDao.save(myRoleUser);

    }


}
